import json,requests
import os
import time
import hashlib,base64
from bs4 import BeautifulSoup
# https://spa2.scrape.center/api/movie/?limit=10&offset=0&token=NmMzY2ZlNjhiZmU3ZDNmYzc2NzM3ZDMwMjFkM2QyN2ZlYmJlYzdlMiwxNzU1NDQwMDgy
class Movies():
    def __init__(self):
        self.url = f'https://spa2.scrape.center/api/movie/?limit=10&offset=0&token=%s'
        self.comment_url = f'https://spa2.scrape.center/api/movie/%s/?token=%s'
        self.headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

    def send_re(self,url):
        response = requests.get(url, headers=self.headers)
        return response

    def send_img(self,url):
        response = requests.get(url, headers=self.headers)
        return response

    def sha1(self,text):
        sha1_hex = hashlib.sha1(text.encode()).hexdigest()
        return sha1_hex

    def base64(self,text):
        base64_text = base64.b64encode(text.encode()).decode()
        return base64_text


    def jiexi(self,result1,page):
        print(result1)
        result_json = result1.json()

        movies = []

        # 遍历每部电影卡片
        for item in result_json.get('results'):
            title_name = item.get('name')
            title_alias = item.get('alias')
            title_cover = item.get('cover')
            title_categories = item.get('categories')
            '''
            1、详情 e
            2、token a
            '''
            href = item.get('id')
            #url参数加密base1
            param_base1 = f'ef34#teuq0btua#(-57w1q5o5--j@98xygimlyfxs*-!i-0-mb{href}'
            url_base_str = self.base64(param_base1)

            #token加密
            '''
            1、把o加密sha1
            2、把c加密base
            '''
            param_base2 = f'/api/movie/{url_base_str},{i * 10},{t}'
            #进行sha加密
            token_sha2_hex = self.sha1(param_base2)
            token_text = f'{token_sha2_hex},{t}'
            #base加密并且转换为str
            token_base = self.base64(token_text)

            new_url = self.comment_url % (url_base_str,token_base)
            print(new_url)

            img_result = self.send_re(new_url)
            comment = img_result.json().get('drama')
            img_result = self.send_img(title_cover)

            with open(f'./img/{title_name}.jpg','wb') as f:
                f.write(img_result.content)
                print(f'已保存{title_name}')

            if title_name:
                movies.append({
                    'page_title': f'第{page}页',
                    'title': title_name,
                    'title_alias': title_alias,
                    'title_cover': title_cover,
                    'title_categories': title_categories,
                    'comment': comment

                })
        return movies

if __name__ == '__main__':
    for i in range(1):
        m = Movies()
        t = int(time.time())
        text = f'/api/movie,{i*10},{t}'
        sha1_hex = m.sha1(text)
        text2 = f'{sha1_hex},{t}'
        token1 = m.base64(text2)
        url = m.url %token1
        print(url)

        result = m.send_re(url)
        aa = m.jiexi(result,i)
        print(f'第{i}页结束')
        print(aa)

        # 1. 读旧数据（若文件不存在则初始化为 []）
        if os.path.exists('result.json'):
            with open('result.json', 'r', encoding='utf-8') as f:
                data = json.load(f)
        else:
            data = []

        if isinstance(data, list):
            data.extend(aa)
        else:
            data.append(aa)

        with open('result.json', 'w+', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)
        time.sleep(1)

        with open('result.json', 'w', encoding='utf-8') as f:
            json.dump(aa, f, ensure_ascii=False, indent=4)

